package org.flower.isme.flower.controller;

import lombok.extern.slf4j.Slf4j;
import org.flower.isme.common.exception.BizException;
import org.flower.isme.common.response.BizResponseCode;
import org.flower.isme.common.response.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/images")
@Slf4j
public class ImageUploadController {

    @Value("${imagepath}")
    private String imagePath;

    @PostMapping("/upload")
    public R<String> uploadImage(@RequestParam("file") MultipartFile file) {
        log.info("Uploading image");
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new BizException(BizResponseCode.ERR_400, "文件为空");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("File name: {}", fileName);
        if (fileName == null) {
            throw new BizException(BizResponseCode.ERR_400, "文件名为空");
        }

        // 创建存储路径
        String newFileName = System.currentTimeMillis() + "_" + fileName;
        File dest = new File(imagePath + File.separator + newFileName);

        try {
            // 保存文件
            file.transferTo(dest);
            log.info("File uploaded successfully");
            String responseName =  "/images/" + newFileName;
            // 返回文件的访问路径
            return R.ok(responseName);
        } catch (IOException e) {
            throw new BizException(BizResponseCode.ERR_400, "上传失败" + e.getMessage());
        }
    }
}
